import React from 'react';
import './socket-demo.css';
import {connect} from 'react-redux'
import {setUserName} from '../redux/user.redux'

@connect(
  null,
  {setUserName}
)
class Login extends React.Component{
  constructor(props) {
    super(props);
    this.state={
      user:''
    }

    this.login=this.login.bind(this)
    this.onKeyDown=this.onKeyDown.bind(this)
  }

  //键盘点击跳转
  onKeyDown(e){
    switch (e.keyCode) {
      case 13:
        this.login();
        return;
      default:
        return;
    }
  }

  //添加键盘事件
  componentDidMount() {
    document.addEventListener("keydown", this.onKeyDown)
  }

  //赋值state
  handleChange(title,target){
    this.setState({
      [title]:target.target.value
    })
  }

  //赋值并跳转到聊天室页面
  login(){
    let {user}=this.state;
    if(user!==null && user.trim()!==''){
      this.props.setUserName(user);
      this.props.history.push('/talk')
    }
  }

  render() {
    return (
      <div className='loginDiv'>
        <input type='text' placeholder='输入昵称' onChange={v=>this.handleChange('user',v)} />
        <button onClick={this.login}>进入聊天室</button>
      </div>
    );
  }
}

export default Login
